<script lang="ts">
  import type { DrawInfo } from "$lib/api/board/board_draw";
  import type { MemberInfo as BoardMemberInfo } from "$lib/api/board/board_member";
  import { list as list_board_member } from "$lib/api/board/board_member";
  import { update_draw_edit_member } from "$lib/api/board/board_draw";
  import { get_user_session } from "$lib/api/user";
  import { request } from "$lib/utils/request";
  import { Modal } from "@skeletonlabs/skeleton-svelte";
  import type { Store as ToastStore } from "@zag-js/toast";
  import { X } from "lucide-svelte";
  import AsyncImage from "$lib/components/image/AsyncImage.svelte";
  import { getContext } from "svelte";

  const toast: ToastStore = getContext("toast");

  interface ModalProps {
    boardId: string;
    drawInfo: DrawInfo;
    canEdit: boolean;
    onClose: () => void;
  }
  let props: ModalProps = $props();

  let memberList = $state([] as BoardMemberInfo[]);
  let editMemberUserIdList = $state(
    props.drawInfo.edit_member_user_id_list.slice()
  );
  let hasChange = $state(false);

  async function loadMemberList() {
    const sessionId = await get_user_session();
    const res = await request(
      list_board_member({
        session_id: sessionId,
        board_id: props.boardId,
      })
    );
    memberList = res.member_list;
  }
  loadMemberList();

  async function updatePerm() {
    const allMemberUserIdList = memberList.map(
      (item) => item.member_user_id
    );
    const newEditMemberUserIdList = editMemberUserIdList.filter((item) =>
      allMemberUserIdList.includes(item)
    );

    const sessionId = await get_user_session();
    await request(
      update_draw_edit_member({
        session_id: sessionId,
        board_id: props.boardId,
        draw_id: props.drawInfo.draw_id,
        edit_member_user_id_list: newEditMemberUserIdList,
      })
    );
    toast.create({
      title: "成功",
      description: "调整权限成功！",
      type: "success",
    });
    props.onClose();
  }
</script>

<Modal
  open={true}
  triggerBase="btn preset-tonal"
  contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl shadow-surface-500 w-[300px]"
  backdropBase="backdrop-none"
  closeOnEscape={false}
  closeOnInteractOutside={false}
  onOpenChange={(ev) => {
    if (!ev.open) {
      props.onClose();
    }
  }}
>
  {#snippet content()}
    <header class="flex justify-between">
      <h4 class="h4">
        {props.canEdit ? "查看/修改权限" : "查看权限"}
      </h4>
      <button
        type="button"
        class="btn preset-ghost-primary-500"
        onclick={() => props.onClose()}
      >
        <X />
      </button>
    </header>

    <main class="pl-2 pr-2 max-h-[calc(100vh-400px)] overflow-y-auto">
      {#each memberList as memberWrap}
        <div class="p-2 flex">
          <div class="flex w-[100px]">
            <AsyncImage
              src={memberWrap.member_logo_uri}
              sizeClass="w-[20px] h-[20px]"
              borderClass="rounded-[10px]"
            />
            {memberWrap.member_display_name}
          </div>
          {#if memberWrap.admin}
            管理员
          {:else}
            <label class="flex gap-2">
              <input
                type="checkbox"
                class="checkbox bg-surface-100-900"
                disabled={!props.canEdit}
                checked={editMemberUserIdList.includes(
                  memberWrap.member_user_id
                )}
                onchange={(e) => {
                  hasChange = true;
                  if (e.currentTarget.checked) {
                    if (
                      !editMemberUserIdList.includes(
                        memberWrap.member_user_id
                      )
                    ) {
                      editMemberUserIdList.push(
                        memberWrap.member_user_id
                      );
                    }
                  } else {
                    editMemberUserIdList = editMemberUserIdList.filter(
                      (item) => item != memberWrap.member_user_id
                    );
                  }
                }}
              />
              修改画稿
            </label>
          {/if}
        </div>
      {/each}
    </main>

    {#if hasChange}
      <footer class="flex justify-end gap-4 m-[10px]">
        <button
          type="button"
          class="btn preset-tonal"
          onclick={() => props.onClose()}>取消</button
        >
        <button
          type="button"
          class="btn preset-filled-primary-900-100"
          onclick={() => updatePerm()}
        >
          更新
        </button>
      </footer>
    {/if}
  {/snippet}
</Modal>
